from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QPushButton
from utils.memoryUtil import PandasSharedMemory
from components.paged_table import PagedTable
import pandas as pd
from PyQt5 import QtCore


class Users(QWidget):
    """
    用户表数据库查询
    """

    reload_table_signal = QtCore.pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.table = PagedTable('users')
        self.init()

        # 连接信号到子控件的方法
        self.reload_table_signal.connect(self.table.init)

    def init(self):
        """
        实例化
        :return:
        """
        vbox = QVBoxLayout()
        hbox = QHBoxLayout()
        button = QPushButton('查询')
        button.clicked.connect(self.search)
        hbox.addWidget(button)
        hbox.addStretch()
        vbox.addLayout(hbox)
        vbox.addWidget(self.table)

        self.setLayout(vbox)
        self.setWindowTitle('菜谱详情')

    def search(self):
        users = self.search_users()
        if not users:
            QMessageBox.warning(None, "警告", "没查查到用户数据")
        df = pd.DataFrame(users)
        del df['password']
        # 用空格替换缺失的值
        df = df.fillna(' ')
        # df = df.set_axis(column_name, axis='columns')

        # 数据转换成表格的使用
        reader = PandasSharedMemory('users')
        read_dt = reader.read_dataframe()
        if read_dt is None:
            writer = PandasSharedMemory('users')
            writer.write_dataframe(df)
        else:
            # 读取示例
            modify = PandasSharedMemory('users')
            modify.modify_dataframe(df)
        self.emit_signal()
        # 调整所有列宽以适应内容
        self.table.resize_columns()

    @staticmethod
    def search_users():
        """
        数据库查询用户
        :return: 用户数据列表
        """
        from utils.dbUtil import DBUtil
        db = DBUtil('mysql')
        users = db.select()
        return users

    def emit_signal(self):
        self.reload_table_signal.emit('users')
